<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>03_深拷贝和浅拷贝-数组拷贝</title>
</head>

<body>

  <script>
    function isObject(value) {
      const valueType = typeof value
      return (value !== null) && (valueType === 'object' || valueType === 'function')
    }
  </script>
  <script>
    function deepClone(origin) {
      if (!isObject(origin)) return origin

      // if (Array.isArray(origin)) {
      //   return JSON.parse(JSON.stringify(origin))
      // }

      const newObj = Array.isArray(origin) ? [] : {}
      for (const key in origin) {
        newObj[key] = deepClone(origin[key])
      }
      return newObj
    }

    const obj = {
      name: "deepClone",
      age: 18,
      address: {
        city: "北京",
        home: {
          name: "home"
        }
      },
      arr: [1, 2, 3]
    }

    const books = [
      { name: "js", price: 100, desc: { intor: "deepClone", info: "这本书讲了一个很有意思的故事"} },
      { name: "你不知道JavaScript", price: 99 },
    ]

    const newObj = deepClone(obj)
    const newArr = deepClone(books)
    obj.arr[1] = 100
    books[0].desc.intor = "new"

    console.log(obj, newObj);
    console.log(books, newArr);
    
    
  </script>

</body>

</html>